package com.my.handler;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.my.enmu.ErrorTypeEnum;
import com.my.service.TokenService;
import com.my.util.Rest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class LoginHandler implements HandlerInterceptor {

    private TokenService service;

    public LoginHandler(TokenService service) {
        this.service = service;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        service.cleanObsoleteToken();
        String token = request.getHeader("authentication-token");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpStatus.HTTP_OK);
            response.getWriter().write("OPTIONS returns OK");
            return true;
        }
        if(service.getById(token) == null) {
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(JSONUtil.toJsonStr(Rest.err(ErrorTypeEnum.ERROR_401, "未登录!")));
            return false;
        }
        service.updateToken(token);
        return true;
    }
}
